<template>
  <div>
    <div class="search_box">
      <el-form :inline="true" :model="formData">
        <el-form-item label="剧目ID或标题">
          <el-input
            v-model="formData.keyword"
            placeholder="剧目ID或标题"
            clearable
          />
        </el-form-item>
        <el-form-item label="标 签">
          <el-select
            v-model="formData.tagIds"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in tagsOption"
              :key="item?.id"
              :label="item.text"
              :value="item?.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList(1)">查 询</el-button>
          <!-- v-auth="'api:agent:apps:search'" -->
          <el-button type="primary" @click="resetList">重 置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table_box_wrapper">
      <div class="batch_box">
        <div>
          <el-button type="primary" @click="addEps">
            <el-icon style="margin-right: 5px">
              <Plus />
            </el-icon>
            新 增
          </el-button>
          <el-button type="primary" @click="getList(1)">
            <el-icon>
              <Refresh />
            </el-icon>
            刷新媒资状态
          </el-button>
        </div>
        <div style="margin-right: 98px">
          <el-button
            type="primary"
            @click="batchPower"
            :disabled="selectionData?.length == 0"
          >
            <el-icon>
              <Finished />
            </el-icon>
            批量授权
          </el-button>
        </div>
      </div>

      <custom-table
        :loading="loading"
        :columns="columns"
        :tableData="tableData"
        :pageObj="pageObj"
        @sizechange="sizechange"
        @currentChange="currentChange"
        :typeSelect="true"
        @selectionChange="selectionChange"
        :isCustomHead="true"
        class="table_box"
      >
        <!-- :typeSelect="true"-->
        <template #desc="{ scope }">
          <el-tooltip
            effect="dark"
            :content="scope.row.desc"
            placement="top"
            v-if="scope.row?.desc && scope.row?.desc.length > 17"
          >
            <div class="overflowTwo name">{{ scope.row.desc }}</div>
          </el-tooltip>
          <div class="overflowTwo name" v-else>{{ scope.row.desc }}</div>
        </template>

        <!-- v-auth="'api:agent:apps:update'" -->
        <template #updateEpisodeNo="{ scope }">
          {{ `${scope.row?.updateEpisodeNo} / ${scope.row?.episodeNum}` }}
        </template>
        <template #tags="{ scope }">
          <el-tag
            v-for="(item, i) in scope.row?.tags"
            :key="i"
            style="margin: 0 3px"
          >
            {{ item.text }}
          </el-tag>
        </template>
        <template #showStatus="{ scope }">
          <el-switch
            style="

--el-switch-on-color: #13ce66"
            :modelValue="scope.row.showStatus === 1"
            inline-prompt
            active-text="是"
            inactive-text="否"
            @click.stop="handdelStatus(scope.row)"
          />
        </template>
        <template #promotionStartTime="{ scope }">
          <span v-if="activeTime(scope.row?.promotionStartTime)" class="red">
            {{ scope.row?.promotionStartTime }}
          </span>
          <el-tag type="success" v-else>已开投</el-tag>
        </template>

        <!-- 媒资状态 -->
        <template #createdUploadTaskAppCountHead>
          <span>媒资状态</span>
          <el-tooltip class="item" effect="light" placement="top">
            <template #content>
              <!-- 同步媒资：还没有小程序在同步媒资文件任务数量 <br /> -->
              <span class="black">黑色数字：</span>剧目同步媒资文件的小程序数量
              <br />
              <span class="green">绿色数字：</span
              >剧目已经上传成功的媒资文件同步任务数量 <br />
              <span class="blue">蓝色数字：</span
              >剧目正在上传中的媒资文件同步任务数量 <br />
              <span class="red">红色数字：</span
              >剧目上传失败的媒资文件同步任务数量
            </template>
            <el-icon class="icon_header">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
        </template>
        <template #createdUploadTaskAppCount="{ scope }">
          <span
            class="operationClick"
            v-if="!scope.row.createdUploadTaskAppCount"
            @click="haddelMediaJump(scope.row, '主小程序')"
          >
            同步媒资
          </span>
          <template v-else>
            <span
              class="hover_text"
              @click="haddelMediaJump(scope.row, '主小程序')"
            >
              {{ scope.row.createdUploadTaskAppCount }}
            </span>
            /
            <span
              class="green hover_text"
              @click="haddelMediaJump(scope.row, '成功')"
            >
              {{ scope.row.uploadedCount }}
            </span>
            /
            <span
              class="blue hover_text"
              @click="haddelMediaJump(scope.row, '进行中')"
            >
              {{ scope.row.uploadingCount }}
            </span>
            /
            <span
              class="red hover_text"
              @click="haddelMediaJump(scope.row, '失败')"
            >
              {{ scope.row.uploadFailedCount }}
            </span>
          </template>
        </template>
        <!-- 审核状态 -->
        <template #reviewAppCountHead>
          <span>剧目提审状态</span>
          <el-tooltip class="item" effect="light" placement="top">
            <template #content>
              <!-- 提审：小程序下的同步媒资文件全部上传成功但还未开始提审 <br /> -->
              <span class="black">黑色数字：</span>
              剧目提审到了多少个小程序的数量
              <br />
              <span class="green">绿色数字：</span>剧目已经提审成功的小程序数量
              <br />
              <span class="blue">蓝色数字：</span>剧目正在提审中的小程序数量
              <br />
              <span class="red">红色数字：</span>剧目提审失败的小程序数量
            </template>
            <el-icon class="icon_header">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
        </template>
        <template #reviewAppCount="{ scope }">
          <span class="grey" v-if="!scope.row.createdUploadTaskAppCount">
            需先媒资同步完成
          </span>
          <template v-else>
            <template v-if="!scope.row.reviewAppCount">
              <span
                class="operationClick"
                @click="haddeReviewlJump(scope.row, '提审')"
              >
                提审
              </span>
            </template>
            <template v-else>
              <span
                class="hover_text"
                @click="haddeReviewlJump(scope.row, '主小程序')"
              >
                {{ scope.row.reviewAppCount }}
              </span>
              /
              <span
                class="green hover_text"
                @click="haddeReviewlJump(scope.row, '成功')"
              >
                {{ scope.row.reviewedAppCount }}
              </span>
              /
              <span
                class="blue hover_text"
                @click="haddeReviewlJump(scope.row, '进行中')"
              >
                {{ scope.row.reviewingAppCount }}
              </span>
              /
              <span
                class="red hover_text"
                @click="haddeReviewlJump(scope.row, '失败')"
              >
                {{ scope.row.reviewFailedAppCount }}
              </span>
            </template>
          </template>
        </template>

        <template #operator="{ scope }">
          <span
            class="operationClick"
            @click.stop="handleActive(scope.row, '授权')"
          >
            分销商授权
          </span>
          <span
            class="operationClick"
            @click.stop="handleActive(scope.row, '取消')"
          >
            取消授权
          </span>
          <span
            class="operationClick"
            @click.stop="handleActive(scope.row, '编辑')"
          >
            编辑
          </span>
          <span
            class="operationClick"
            @click.stop="handleActive(scope.row, '拼剧')"
          >
            拼剧
          </span>
        </template>
      </custom-table>
    </div>

    <!-- 分配授权分销商 -->
    <distributor
      ref="distributorRef"
      @success="getList(1)"
      :isMultiple="true"
      :title="'分销商授权'"
      :btnText="'授权'"
      :typePower="2"
    />

    <!-- 取消分销商 分配授权-->
    <distributor
      ref="cancelDistributorRef"
      @success="getList(1)"
      :isMultiple="true"
      :title="'取消分销商授权'"
      :btnText="'取消授权'"
      :batchBtnText="'批量取消'"
      :typePower="2"
    />

    <!-- 任务详情 -->
    <taskDetail ref="taskDetailRef" />

    <!-- 提审剧目详情 -->
    <reviewDetail ref="reviewDetailRef" />

    <!-- 错误原因显示 -->
    <reviewFail ref="reviewFailRef" />

    <!-- 拼剧 -->
    <concatOperas ref="concatOperasRef" @success="getList(1)" />
  </div>
</template>

<script setup lang="ts">
import reviewFail from "./components/reviewFail.vue";
import customTable from "@/components/CustomTable/index.vue";
import distributor from "@/components/Distributor/index.vue";
import taskDetail from "./components/taskDetail.vue";
import reviewDetail from "./components/reviewDetail.vue";
import concatOperas from "./components/concatOperas.vue";
import { updateAppStatus } from "@/api/operateCenter/apps/index";
import {
  operasTags,
  operasSearch,
  showStatus,
} from "@/api/operateCenter/episode/index";
import type { Action } from "element-plus";
import moment from "moment";
import { reactive, ref } from "vue";
import {
  Plus,
  Refresh,
  QuestionFilled,
  Finished,
} from "@element-plus/icons-vue";
import router from "@/router";

const loading = ref<boolean>(false);
const tableData = ref<Array<any>>([]);
const selectionData = ref<Array<any>>([]);
const tagsOption = ref<Array<any>>([]);
const reviewFailRef = ref();
const reviewFailData = ref(
  JSON.parse(localStorage.getItem("reviewFail") as string)
);

const form = {
  keyword: "",
  tagIds: [],
  pageNo: 1,
  pageSize: 10,
};

const formData = reactive(Object.assign({}, form));
interface modelPage {
  pageNo: number;
  pageSize: number;
  total: number;
}
const pageObj = reactive<modelPage>({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

const columns = reactive([
  { label: "Id", prop: "id", minWidth: 80, fixed: "left" },
  { label: "剧目", prop: "name", minWidth: 100 },
  { label: "备注", prop: "desc", slotName: "desc", minWidth: 150 },
  {
    label: "开投时间",
    prop: "promotionStartTime",
    slotName: "promotionStartTime",
    minWidth: 160,
  },
  {
    label: "已发布/总集数",
    prop: "updateEpisodeNo",
    slotName: "updateEpisodeNo",
    minWidth: 115,
  },
  { label: "默认收费卡点", prop: "chargeEpisodeNo", minWidth: 110 },
  { label: "最大收费卡点", prop: "chargeEpisodeNoUpperLimit", minWidth: 110 },
  { label: "默认单价(金币)", prop: "unblockCoinAmount", minWidth: 118 },
  { label: "最小单价(金币)", prop: "unblockCoinAmountMinLimit", minWidth: 118 },
  { label: "排序", prop: "appGhId", minWidth: 60 },
  { label: "标签", prop: "tags", slotName: "tags", minWidth: 200 },
  {
    label: "小程序展示",
    prop: "showStatus",
    slotName: "showStatus",
    minWidth: 150,
  },
  {
    label: "媒资状态",
    prop: "createdUploadTaskAppCount",
    slotName: "createdUploadTaskAppCount",
    slotHeader: "createdUploadTaskAppCountHead",
    minWidth: 120,
  },
  {
    label: "剧目提审状态",
    prop: "reviewAppCount",
    slotName: "reviewAppCount",
    slotHeader: "reviewAppCountHead",
    minWidth: 150,
  },
  {
    label: "操作",
    prop: "operator",
    slotName: "operator",
    fixed: "right",
    width: 260,
  },
]);

// 媒资状态
const taskDetailRef = ref();
const haddelMediaJump = (row: Record<string, any>, str: string) => {
  if (str === "主小程序") {
    router.push(`/operate/episode-media?id=${row?.id}&name=${row?.name}`);
  } else {
    taskDetailRef.value.showDialog(row, str);
  }
};

// 提审状态
const reviewDetailRef = ref();
const haddeReviewlJump = (row: Record<string, any>, str: string) => {
  if (str === "提审") {
    router.push(`/operate/episode-review?id=${row?.id}`);
  } else if (str === "主小程序") {
    router.push(`/operate/episode-review?id=${row?.id}&step=2`);
  } else {
    reviewDetailRef.value.showDialog(row, str);
  }
};

// 开关
const handdelStatus = (val: Record<string, any>) => {
  ElMessageBox.alert(
    `确定要${val?.showStatus == 1 ? "隐藏" : "展示"} "${
      val?.name
    }"剧目绑定的小程序吗？`,
    "提醒",
    {
      confirmButtonText: "确定",
      callback: (action: Action) => {
        if (action === "confirm") {
          let params = {
            id: val.id,
            showStatus: val.showStatus ? 0 : 1,
          };
          showStatus(params).then(() => {
            ElMessage.success(`${val?.showStatus ? "隐藏" : "展示"}成功`);
            getList(1);
          });
        }
      },
    }
  );
};

const getList = (val = 0) => {
  // if (!val) {
  //   formData.pageNo = pageObj.pageNo;
  //   formData.pageSize = pageObj.pageSize;
  // } else {
  //   formData.pageNo = pageObj.pageNo = val === 1 ? val : 1;
  //   formData.pageSize = pageObj.pageSize = val === 1 ? 10 : pageObj.pageSize;
  // }
  formData.pageNo = pageObj.pageNo;
  formData.pageSize = pageObj.pageSize;

  loading.value = true;
  operasSearch(formData)
    .then((res: Record<string, any>) => {
      tableData.value = res.data.map((item: Record<string, any>) => {
        item.premiereTime = moment(item.premiereTime + "Z").format(
          "YYYY-MM-DD HH:mm:ss"
        );
        item.promotionStartTime = moment(item.promotionStartTime + "Z").format(
          "YYYY-MM-DD HH:mm:ss"
        );
        return item;
      });
      pageObj.total = Number(res?.total);
    })
    .finally(() => {
      loading.value = false;
    });
};

// 重置
const resetList = () => {
  Object.assign(formData, form);
  getList(1);
};

// 新增
const addEps = () => {
  router.push("/operate/episode-add");
};

// 编辑 / 分销商授权
const distributorRef = ref();
const cancelDistributorRef = ref();
const concatOperasRef = ref();
const handleActive = (val: Record<string, any>, str: string) => {
  if (str === "编辑") {
    router.push(`/operate/episode-update?id=${val.id}`);
  } else if (str === "授权") {
    distributorRef.value.showDialog(val);
  } else if (str === "取消") {
    cancelDistributorRef.value.showDialog(val);
  } else if (str === "拼剧") {
    concatOperasRef.value.showDialog(val);
  }
};

// 批量授权
const batchPower = () => {
  let seletData = selectionData.value;
  distributorRef.value.showDialog(seletData);
};

// 启用禁用
const handleStatus = (val: Record<string, any>) => {
  let params = {
    appId: val?.id,
    status: val?.status === 1 ? 0 : 1,
  };
  updateAppStatus(params).then(() => {
    ElMessage.success(`${val?.status ? "禁用" : "启用"}成功`);
    getList(1);
  });
};

// 获取标签下拉选项
const getTags = () => {
  operasTags().then((res: any) => {
    tagsOption.value = res || [];
  });
};

const activeTime = (Time: string) => {
  let now = Date.now();
  let openTime = moment(Time).valueOf();
  return openTime > now ? true : false;
};

const currentChange = (val: number) => {
  pageObj.pageNo = val;
  getList();
};

const sizechange = (val: number) => {
  pageObj.pageSize = val;
  getList(2);
};

const selectionChange = (val: Array<any>) => {
  selectionData.value = val;
};

onMounted(() => {
  getList();
  getTags();
  if (reviewFailData.value && reviewFailData.value.length) {
    console.log("reviewFailData.value---", reviewFailData.value);
    reviewFailRef.value.showDialog(reviewFailData.value);
  }
});

onUnmounted(() => {
  localStorage.removeItem("reviewFail");
});
</script>

<style lang="scss" scoped>
.table_box_wrapper {
  padding-top: 10px;
  margin-top: 15px;
  background-color: #fff;

  .allocation_app {
    padding: 12px 0 5px 10px;
  }

  .hover_text {
    cursor: pointer;
  }

  .hover_text:hover {
    text-decoration: underline;
  }

  .batch_box {
    display: flex;
    justify-content: space-between;
    padding: 0 12px;
  }
}

.table_box {
  padding: 10px;
  border-radius: 4px;

  .movie_box {
    display: flex;
    align-items: center;

    img {
      width: 72px;
      height: 108px;
      margin-right: 12px;
    }
  }

  .icon_header {
    margin-left: 2px;
    font-size: 15px;
    vertical-align: text-top;
  }
}
</style>
